package show.me.the.money.dictionary;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;

public class CustomDictionary extends XMLDictionary {
	
	private static final Log logger = LogFactory.getLog(CustomDictionary.class);
	private Element define;
	private String clazz;
	private String method;
	private HashMap<String, String> propFilter = new HashMap<String, String>();

	@SuppressWarnings("unchecked")
	public void setDefineDoc(Document doc) {
		if(doc == null){
			logger.error("init failed,can't get dic define");
			return;
		}
		define = doc.getRootElement();
		Element eclazz = (Element) define.selectSingleNode("arg[@name='class']");
		Element emethod = (Element) define.selectSingleNode("arg[@name='method']");
		if(define.selectSingleNode("arg[@name='filter']") != null){
			Element filter = (Element) define.selectSingleNode("arg[@name='filter']");
			List<Element> es = filter.elements("prop");
			for(Element e : es){
				propFilter.put(e.attributeValue("name"), e.getText().trim());
			}
		}
		if(eclazz == null || emethod == null){
			logger.error("class or method args missing .");
			return;			
		}
		clazz = eclazz.getText();
		method = emethod.getText();
		try {
			Object obj = Class.forName(clazz).newInstance();
			Method m = obj.getClass().getMethod(method);
			define = ((Document) m.invoke(obj)).getRootElement();
		} catch (Exception e) {
			logger.error("get custom dic["+clazz+"],method["+method+"] occur error.");
			logger.error(e.getMessage(),e);
			return;
		}
		super.setDefineDoc(define.getDocument());
	}
	
}
